<template>
  <div class="search-form" @keydown.enter="emit('search')">
    <div
      class="flex p-2 rounded-md search-form-content justify-between items-start"
      :class="expand ? 'search-form-expand' : ''"
      :style="{ background: token.colorBgContainer }"
    >
      <div ref="slotRef" class="flex-1"><slot></slot></div>
      <div class="min-w-[185px] flex justify-end items-center">
        <a-button v-if="isShowExpand" type="link" class="text-xs mr-2" @click="expand = !expand">
          <UpOutlined v-if="expand" /> <DownOutlined v-else />展开
        </a-button>
        <a-button @click="handleReset">重置</a-button>
        <a-button class="ml-2" type="primary" @click="handleSearch">{{ searchText }}</a-button>
        <a-button v-if="showExport" class="ml-2" :disabled="!exportDisabled" type="primary" @click="emit('export')">导出</a-button>
      </div>
    </div>
  </div>
</template>
<script setup>
import { ref, onMounted, watch } from 'vue'
import { DownOutlined, UpOutlined } from '@ant-design/icons-vue'
import { theme } from 'ant-design-vue'
import useThemeStore from '@/store/theme'

defineProps({
  searchText: {
    type: String,
    default: '搜索'
  },
  exportDisabled: {
    type: Boolean,
    default: true
  },
  showExport: {
    type: Boolean,
    default: false
  }
})
const themeStore = useThemeStore()
const appSizeEnums = {
  small: 38,
  middle: 48,
  large: 54
}
const expand = ref(false)
const height = ref('48px')
const isShowExpand = ref(false)
const { useToken } = theme
const { token } = useToken()
watch(
  () => themeStore.appSize,
  (val) => {
    if (val) {
      height.value = appSizeEnums[val] + 'px'
    }
  }
)
const emit = defineEmits(['search', 'reset', 'export'])
const slotRef = ref(null)
onMounted(() => {
  //显示展开按钮
  height.value = appSizeEnums[themeStore.appSize] + 'px'
  calcHeight()
})
const calcHeight = () => {
  setTimeout(() => {
    const offsetHeight = slotRef.value?.querySelector('.ant-form').offsetHeight
    isShowExpand.value = offsetHeight > 63
  }, 300)
}
const handleSearch = () => {
  expand.value = false
  emit('search')
}
const handleReset = () => {
  emit('reset')
  emit('search')
}
defineExpose({
  calcHeight
})
// const onClickOutside = () => {
//   expand.value = false
// }
</script>
<style lang="less" scoped>
.search-form {
  position: relative;
  height: v-bind(height);
  min-height: 48px;
  .search-form-content {
    position: absolute;
    z-index: 9;
    width: 100%;
    height: v-bind(height);
    overflow: hidden;
  }
  .search-form-expand {
    height: fit-content;
    box-shadow: 2px 5px 5px 2px rgba(0, 0, 0, 0.2);
  }
  :deep(.ant-form-item) {
    margin-bottom: 8px;
  }
}
</style>
